# -*- coding:utf-8 -*-

import requests
from lxml import etree
from fake_useragent import UserAgent
from http import cookiejar
import json
from datetime import datetime
import time
import re
import execjs
from utils.HttpUtils import HttpUtils


requests.packages.urllib3.disable_warnings()  # 忽略HTTPS安全警告


"""
七麦-获取app榜单
https://www.qimai.cn/rank
"""

class Test_Get():
    def __init__(self):
        #声明一个CookieJar对象实例来保存cookie
        self.cookie = cookiejar.CookieJar()
        ua = UserAgent(use_cache_server=False)  # 禁用服务器缓存
        self.headers = {
            # "User-Agent": ua.random
            # 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1 Safari/605.1.15'
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36",
            "Content-Type": "application/x-www-form-urlencoded",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        }
        self.cookies = dict()


    def get_contents(self, current):
        resp = HttpUtils.do_request("GET", "https://www.qimai.cn/rank", self.headers, "")
        self.cookies.update(resp.cookies.get_dict())
        synct = self.cookies.get('synct')
        postData = {
            'brand': 'all',
            'country': 'cn',
            'device': 'iphone',
            'genre': '5000',
            'date': '2020-03-19',
            "is_rank_index":1,
            'page': 1    # 这里写1也是可以的
        }
        page = 0  # 0付费榜 1免费榜 2畅销榜
        url = f"https://api.qimai.cn/rank/indexPlus/brand_id/{page}"
        analy_list = self.getanaly(synct, postData)
        postData['analysis'] = analy_list[page]
        resp = requests.get(url=url, params=postData, headers=self.headers, verify=False, cookies=self.cookies)
        data_json = json.loads(resp.text)
        contents = data_json['list']
        for content in contents:
            appInfo = content['appInfo']
            print(appInfo)


    # 加密参数
    def getanaly(self, synct, params):
        with open("qimai_decrypt.js", 'r', encoding="utf-8") as f:
            js_content = f.read()
            ctx = execjs.compile(js_content)
            new_pwd = ctx.call("get0analysis", synct, params)
            return new_pwd


if __name__ == '__main__':
    test_get = Test_Get()
    test_get.get_contents("")

